package com.space.school.dao.impl;

import com.space.school.dao.DetailDao;
import com.space.school.domain.Detail;
import com.space.school.domain.Master;
import com.space.school.utils.KeyUtil;
import com.space.school.utils.SpaceJDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

public class DetailDaoImpl implements DetailDao {
    //    获取数据库链接
    private JdbcTemplate jdbcTemplate=new JdbcTemplate(SpaceJDBCUtils.getDataSource());

    @Override
    public void del(String order_id) {
        String sql = "delete from order_detail where order_id=?";
        jdbcTemplate.update(sql,order_id);

    }

    @Override
    public void add(Detail detail) {
        Long a= Long.valueOf(KeyUtil.generateKey());
        String sql = "insert into order_detail(detail_id,order_id,product_id,create_time,product_num) values(?,?,?,?,?)";
        jdbcTemplate.update(sql,a,detail.getOrder_id(),detail.getProduct_id(),new Date(),detail.getProduct_num());
    }

    @Override
    public int find_product_num(Detail detail) {
        String sql = "select sum(product_num) from order_detail  where product_id=?";
        if( jdbcTemplate.queryForObject(sql,Integer.class,detail.getProduct_id())==null){
            return 0;
        }else {
            return jdbcTemplate.queryForObject(sql,Integer.class,detail.getProduct_id());
        }
    }


    @Transactional
//    事物 相当于把sql形成一个整体 要么全成功要么全失败
//    带锁的概念 如果在你查询的时候,别人想修改数据,别人会进行一个等待,等待查询完事再进行更新
//    如果存在多个SQL语句的时候,如果出现一个错误,会进行一个事物回滚


    @Override
    public List<Master> find_sum(Long order_id ) {
        String sql = "SELECT sum(detail.product_num) order_amount,sum(info.product_price*detail.product_num) order_total FROM order_detail detail LEFT JOIN product_info info ON info.product_id=detail.product_id where order_id=?";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<Master>(Master.class),order_id);
    }



}
